package com.ray.finance.api;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ray.base.service.BaseCustomerService;
import com.ray.base.service.compose.GoodsService;
import com.ray.base.table.entity.BaseCustomer;
import com.ray.base.table.vo.material.model.MaterialModelVO;
import com.ray.business.builder.BusinessGoodsVOBuilder;
import com.ray.business.builder.PurchaseGoodsBuilder;
import com.ray.business.enums.BusinessTypeEnum;
import com.ray.business.service.*;
import com.ray.business.service.compose.BusinessService;
import com.ray.business.service.compose.PurcahseService;
import com.ray.business.service.compose.SaleService;
import com.ray.business.table.entity.*;
import com.ray.business.table.vo.BusinessGoodsVO;
import com.ray.business.table.vo.BusinessVO;
import com.ray.business.table.vo.PurchaseGoodsVO;
import com.ray.common.SysMsgCodeConstant;
import com.ray.common.check.AbstractCheck;
import com.ray.finance.builder.BillBuilder;
import com.ray.finance.builder.BillPayBuilder;
import com.ray.finance.builder.BillVOBuilder;
import com.ray.finance.check.BillCheck;
import com.ray.finance.enums.BillSourceEnum;
import com.ray.finance.enums.BillStatusEnum;
import com.ray.finance.enums.BillTypeEnum;
import com.ray.finance.enums.PayTypeEnum;
import com.ray.finance.service.FinaBillAdjustService;
import com.ray.finance.service.FinaBillPayService;
import com.ray.finance.service.FinaBillService;
import com.ray.finance.service.compose.AdvanceService;
import com.ray.finance.table.dto.BillAmountChangeDTO;
import com.ray.finance.table.dto.BillCountDTO;
import com.ray.finance.table.dto.BillCountQueryDTO;
import com.ray.finance.table.dto.BillQueryDTO;
import com.ray.finance.table.entity.FinaAdvance;
import com.ray.finance.table.entity.FinaBill;
import com.ray.finance.table.params.bill.BillAdjuestQueryParams;
import com.ray.finance.table.params.bill.BillCountQueryParams;
import com.ray.finance.table.params.bill.BillCreateParams;
import com.ray.finance.table.params.bill.BillQueryParams;
import com.ray.finance.table.vo.BillCountVO;
import com.ray.finance.table.vo.BillVO;
import com.ray.magicBlock.BlockDispatch;
import com.ray.system.builder.CommonPageBuilder;
import com.ray.woodencreate.beans.LoginUser;
import com.ray.woodencreate.exception.BusinessExceptionFactory;
import com.ray.woodencreate.page.CommonPage;
import com.ray.woodencreate.result.MsgCodeConstant;
import com.ray.woodencreate.result.Result;
import com.ray.woodencreate.result.ResultFactory;
import com.ray.woodencreate.util.Assert;
import com.ray.woodencreate.util.LogInUserUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.validation.Valid;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author bo shen
 * @Description: 对账单
 * @Class: BillApi
 * @Package com.ray.finance.api
 * @date 2020/6/15 15:35
 * @company <p>Ray快速开发平台</p>
 * @updateRecord time(修改时间)  author(修改人)   desc(修改内容)
 */
@Slf4j
@Service
public class BillApi {

    @Autowired
    private FinaBillService finaBillService;
    @Autowired
    private FinaBillAdjustService finaBillAdjustService;
    @Autowired
    private FinaBillPayService finaBillPayService;
    @Autowired
    private BaseCustomerService baseCustomerService;
    @Autowired
    private BillAdjustApi billAdjustApi;
    @Autowired
    private BusinessService businessService;
    @Autowired
    private BlockDispatch<BillCreateParams, LoginUser, String> createDispatch;
    @Autowired
    private BlockDispatch<String, LoginUser, List<?>> goodsListDispatch;
    @Autowired
    private BlockDispatch<FinaBill, LoginUser, String> cancelDispatch;
    @Autowired
    private PurcahseService purcahseService;
    @Autowired
    private SaleService saleService;
    @Autowired
    private AdvanceService advanceService;
    @Autowired
    private ProdPurchaseInRecordService prodPurchaseInRecordService;
    @Autowired
    private ProdPurchaseInService prodPurchaseInService;
    @Autowired
    private ProdPurchaseBackRecordService prodPurchaseBackRecordService;
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private ProdBusinessInService prodBusinessInService;
    @Autowired
    private ProdBusinessService prodBusinessService;

    /**
     * 查询订单列表信息 分页  非删除的
     *
     * @param queryParams
     * @return
     */
    public Result<IPage<BillVO>> pageBillss(CommonPage<BillQueryParams, Page<BillVO>> queryParams) {
        Assert.notNull(queryParams, SysMsgCodeConstant.Error.ERR10000001);
        //当前登录对象
        LoginUser loginUser = LogInUserUtil.get();
        Map<String, BaseCustomer> baseCustomerMap = new HashMap<>();
        CommonPageBuilder<BillQueryDTO, FinaBill> commonPageBuilder = new CommonPageBuilder<>(BillQueryDTO.class);
        commonPageBuilder.appendEntity(queryParams.getEntity()).appendQuery(queryParams.getQuery()).appendPage(queryParams.getPage());
        IPage<FinaBill> page = finaBillService.page(commonPageBuilder.bulid(), loginUser);
        List<FinaBill> orders = page.getRecords();
        //结果对象
        IPage<BillVO> pageList = new Page<>();
        pageList.setTotal(page.getTotal());
        pageList.setCurrent(page.getCurrent());
        pageList.setSize(page.getSize());
        //查询到结果 数据转换
        if (ObjectUtil.isNotNull(orders)) {
            pageList.setRecords(orders.stream().map(sysBill -> {
                //查询客信息
                BaseCustomer baseCustomer = baseCustomerMap.get(sysBill.getCustomerCode());
                if (ObjectUtil.isEmpty(baseCustomer)) {
                    baseCustomer = baseCustomerService.queryCustomerByCustomerCode(sysBill.getCustomerCode(), loginUser);
                    baseCustomerMap.put(sysBill.getCustomerCode(), baseCustomer);
                }
                BillVOBuilder orderVOBuilder = new BillVOBuilder();
                orderVOBuilder.append(sysBill).append(baseCustomer);
                return orderVOBuilder.bulid();
            }).collect(Collectors.toList()));
        } else {
            pageList.setRecords(new ArrayList<>());
        }
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000002, pageList);
    }


    /**
     * 创建加工业务入库单
     *
     * @return
     */
    @Transactional
    public Result<String> createBusinessBill(BillCreateParams createParams, BillSourceEnum billSourceEnum) {
        //当前登录对象
        LoginUser loginUser = LogInUserUtil.get();
        String billNo = createDispatch.dispatch("createBill", billSourceEnum.getValue(), createParams, loginUser);
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000002, billNo);
    }

    /**
     * 取消
     *
     * @return
     */
    @Transactional
    public Result<String> cancelBill(String billNo) {
        Assert.hasLength(billNo, "参数[billNo]不能为空");
        //当前登录对象
        LoginUser loginUser = LogInUserUtil.get();
        FinaBill finaBill = finaBillService.queryBillByBillNo(billNo, loginUser);
        new BillCheck(finaBill).checkNull("对账单不存在").checkCanCancel("对账单不能取消");
        //取消业务单
        cancelDispatch.dispatch("cancelBill", finaBill.getBillSource(), finaBill, loginUser);
        finaBillAdjustService.deleteByBillNo(billNo, loginUser);
        finaBillPayService.deleteByBillNo(billNo, loginUser);
        //取消对应的预付款金额
        advanceService.cancelAdvice(billNo, loginUser);
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000002, billNo);
    }

    /**
     * 删除
     *
     * @return
     */
    @Transactional
    public Result<String> deleteBill(String billNo) {
        Assert.hasLength(billNo, "参数[billNo]不能为空");
        //当前登录对象
        LoginUser loginUser = LogInUserUtil.get();
        FinaBill finaBill = finaBillService.queryBillByBillNo(billNo, loginUser);
        new BillCheck(finaBill).checkNull("对账单不存在").checkCanDelete("对账单不能删除");
        BillBuilder billBuilder = new BillBuilder();
        billBuilder.appendEdit(loginUser).appendCode(finaBill.getBillNo()).delete();
        finaBillService.edit(billBuilder.bulid(), loginUser);
        //取消业务单
        cancelDispatch.dispatch("cancelBill", finaBill.getBillSource(), finaBill, loginUser);
        finaBillAdjustService.deleteByBillNo(billNo, loginUser);
        finaBillPayService.deleteByBillNo(billNo, loginUser);
        //取消对应的预付款金额
        advanceService.cancelAdvice(billNo, loginUser);
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000002, billNo);
    }


    /**
     * 完成
     *
     * @return
     */
    @Transactional
    public Result<String> finishBill(String billNo) {
        Assert.hasLength(billNo, "参数[billNo]不能为空");
        //当前登录对象
        LoginUser loginUser = LogInUserUtil.get();
        FinaBill finaBill = finaBillService.queryBillByBillNo(billNo, loginUser);
        new BillCheck(finaBill).checkNull("对账单不存在").checkCanFinish("对账单不能完成");
        BillBuilder billBuilder = new BillBuilder();
        billBuilder.appendEdit(loginUser).appendCode(finaBill.getBillNo()).appendTime(LocalDateTime.now()).appendOrderStatus(BillStatusEnum.FINISH.getValue());
        finaBillService.edit(billBuilder.bulid(), loginUser);
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000002, billNo);
    }


    /**
     * 删除
     *
     * @return
     */
    @Transactional
    public Result<String> passBill(String billNo) {
        Assert.hasLength(billNo, "参数[billNo]不能为空");
        //当前登录对象
        LoginUser loginUser = LogInUserUtil.get();
        FinaBill finaBill = finaBillService.queryBillByBillNo(billNo, loginUser);
        new BillCheck(finaBill).checkNull("对账单不存在").checkCanCheck("对账单已审核");
        BillBuilder billBuilder = new BillBuilder();
        billBuilder.appendEdit(loginUser).appendCode(finaBill.getBillNo()).appendOrderStatus(BillStatusEnum.PASS.getValue());
        finaBillService.edit(billBuilder.bulid(), loginUser);
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000002, billNo);
    }

    /**
     * 对账单详情
     *
     * @param billNo
     * @return
     */
    public Result<BillVO> viewBill(String billNo) {
        Assert.hasLength(billNo, "参数[billNo]不能为空");
        //当前登录对象
        LoginUser loginUser = LogInUserUtil.get();
        FinaBill finaBill = finaBillService.queryBillByBillNo(billNo, loginUser);
        new BillCheck(finaBill).checkNull("对账单不存在");
        //查询客信息
        BaseCustomer baseCustomer = baseCustomerService.queryCustomerByCustomerCode(finaBill.getCustomerCode(), loginUser);
        BillVOBuilder orderVOBuilder = new BillVOBuilder();
        orderVOBuilder.append(finaBill).append(baseCustomer);
        //对账详情
        if (StrUtil.equals(finaBill.getBillSource(), BillSourceEnum.BUSINESS.getValue())) {
            List<BusinessVO> businessVOS = businessService.queryBusinessByBIllNo(billNo, baseCustomer.getCustomerName(), loginUser);
            orderVOBuilder.appendBusiness(businessVOS);
        }
        //对账详情
        if (StrUtil.equals(finaBill.getBillSource(), BillSourceEnum.PURCHASE.getValue())) {
            List<BusinessVO> businessVOS = purcahseService.queryPurchaseByBIllNo(billNo, baseCustomer.getCustomerName(), loginUser);
            orderVOBuilder.appendBusiness(businessVOS);
        }

        //对账详情
        if (StrUtil.equals(finaBill.getBillSource(), BillSourceEnum.SALE.getValue())) {
            List<BusinessVO> businessVOS = saleService.querySaleByBIllNo(billNo, baseCustomer.getCustomerName(), loginUser);
            orderVOBuilder.appendBusiness(businessVOS);
        }
        //对账详情
        if (StrUtil.equals(finaBill.getBillSource(), BillSourceEnum.ORDER.getValue())) {
            List<BusinessVO> businessVOS = saleService.querySaleByBIllNo(billNo, baseCustomer.getCustomerName(), loginUser);
            orderVOBuilder.appendBusiness(businessVOS);
        }
        //调整详情
        BillAdjuestQueryParams queryParams = new BillAdjuestQueryParams();
        queryParams.setBillNo(finaBill.getBillNo());
        orderVOBuilder.append(billAdjustApi.queryAdjusts(queryParams).getData());
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000002, orderVOBuilder.bulid());
    }


    /**
     * @param queryParams
     * @param billType
     * @return
     */
    public Result<List<BillCountVO>> billCount(BillCountQueryParams queryParams, String billType) {
        //当前登录对象
        LoginUser loginUser = LogInUserUtil.get();
        BillCountQueryDTO billCountQueryDTO = new BillCountQueryDTO();
        BeanUtil.copyProperties(queryParams, billCountQueryDTO);
        billCountQueryDTO.setBillType(billType);
        billCountQueryDTO.setCompanyCode(loginUser.getCompanyCode());
        List<BillCountVO> billCountVOList = finaBillService.countAmount(billCountQueryDTO)
                .parallelStream().map(billCountDTO -> {
                    BillCountVO billCountVO = new BillCountVO();
                    BeanUtil.copyProperties(billCountDTO, billCountVO);
                    //查询客户信息
                    BaseCustomer baseCustomer = baseCustomerService.queryCustomerByCustomerCode(billCountDTO.getCustomerCode(), loginUser);
                    if (ObjectUtil.isNotNull(baseCustomer)) {
                        billCountVO.setCustomerName(baseCustomer.getCustomerName());
                    }
                    return billCountVO;
                }).collect(Collectors.toList());
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000002, billCountVOList);
    }

    /**
     * 采购单明细
     *
     * @param createParams
     * @return
     */
    public Result<List<PurchaseGoodsVO>> pruchaseGoodsList(@Valid BillCreateParams createParams) {
        //当前登录对象
        LoginUser loginUser = LogInUserUtil.get();
        //查询采购单列表
        List<String> orderNos = createParams.getOrderNos();
        if (ObjectUtil.isEmpty(orderNos)) {
            return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000002, new ArrayList<>());
        }
        Map<String, ProdPurchaseInRecord> inRecordMap = new HashMap<>();
        //查询完成的订单
        List<String> finishNos = prodPurchaseInService.listFinishByOrderNos(orderNos, loginUser).stream().map(ProdPurchaseIn::getInCode).collect(Collectors.toList());
        //入库数据
        List<ProdPurchaseInRecord> records = prodPurchaseInRecordService.listByInCodes(finishNos, loginUser);
        //处理数据
        records.forEach(prodPurchaseInRecord -> {
            String key = String.format("%s_%s", prodPurchaseInRecord.getOrderNo(), prodPurchaseInRecord.getGoodsCode());
            ProdPurchaseInRecord inRecord = inRecordMap.get(key);
            if (ObjectUtil.isNull(inRecord)) {
                inRecordMap.put(key, prodPurchaseInRecord);
            } else {
                inRecord.setQuantity(inRecord.getQuantity().add(prodPurchaseInRecord.getQuantity()));
                inRecord.setTotal(inRecord.getTotal() + prodPurchaseInRecord.getTotal());
            }
        });
        //退货数据
        List<ProdPurchaseBackRecord> backRecords = prodPurchaseBackRecordService.listByOrderNo(orderNos, loginUser);
        //处理数据
        backRecords.forEach(prodPurchaseBackRecord -> {
            String key = String.format("%s_%s", prodPurchaseBackRecord.getOrderNo(), prodPurchaseBackRecord.getGoodsCode());
            ProdPurchaseInRecord inRecord = inRecordMap.get(key);
            if (ObjectUtil.isNotNull(inRecord)) {
                inRecord.setQuantity(inRecord.getQuantity().subtract(prodPurchaseBackRecord.getQuantity()));
                inRecord.setTotal(inRecord.getTotal() - (prodPurchaseBackRecord.getTotal()));
            }
        });

        Map<String, MaterialModelVO> modelMap = new HashMap<>();
        final List<BigDecimal> totalPriceList = new ArrayList<>();
        final List<BigDecimal> quantity = new ArrayList<>();
        List<PurchaseGoodsVO> purchaseGoodsVOS = inRecordMap.values().stream().map(prodPurchaseRecord -> {
            MaterialModelVO materialModelVO = modelMap.get(prodPurchaseRecord.getGoodsCode());
            if (ObjectUtil.isNull(materialModelVO)) {
                materialModelVO = goodsService.queryGoodsByCode(prodPurchaseRecord.getGoodsCode(), loginUser);
                modelMap.put(prodPurchaseRecord.getGoodsCode(), materialModelVO);
            }
            totalPriceList.add(prodPurchaseRecord.getQuantity().multiply(prodPurchaseRecord.getPrice()));
            quantity.add(prodPurchaseRecord.getQuantity());
            return new PurchaseGoodsBuilder().append(prodPurchaseRecord).append(materialModelVO)
                    .appendTotalAmount(prodPurchaseRecord.getQuantity().multiply(prodPurchaseRecord.getPrice())).bulid();
        }).collect(Collectors.toList());
        //计算总价
        PurchaseGoodsVO purchaseGoodsVO = new PurchaseGoodsVO();
        purchaseGoodsVO.setOrderNo("合计:");
        purchaseGoodsVO.setTotalAmount(totalPriceList.stream().reduce(BigDecimal::add).get());
        purchaseGoodsVO.setQuantity(quantity.stream().reduce(BigDecimal::add).get());
        purchaseGoodsVOS.add(purchaseGoodsVO);
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000002, purchaseGoodsVOS);
    }

    public Result<List<BillCountVO>> billAllCount(@Valid BillCountQueryParams queryParams) {
        //当前登录对象
        LoginUser loginUser = LogInUserUtil.get();
        List<BillCountVO> billCountVOList = new ArrayList<>();
        billCountVOList.addAll(queryAllAmount("收款", BillTypeEnum.IN.getValue(), queryParams, loginUser));
        billCountVOList.addAll(queryAllAmount("付款", BillTypeEnum.OUT.getValue(), queryParams, loginUser));
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000002, billCountVOList);
    }

    /**
     * 统计总费用
     *
     * @param typeName
     * @param billType
     * @param queryParams
     * @param loginUser
     * @return
     */
    private List<BillCountVO> queryAllAmount(String typeName, String billType, BillCountQueryParams queryParams, LoginUser loginUser) {
        BillCountQueryDTO billCountQueryDTO = new BillCountQueryDTO();
        BeanUtil.copyProperties(queryParams, billCountQueryDTO);
        billCountQueryDTO.setBillType(billType);
        billCountQueryDTO.setCompanyCode(loginUser.getCompanyCode());
        List<BillCountDTO> billCountDTOs = finaBillService.countAllAmount(billCountQueryDTO);

        return billCountDTOs.stream().map(billCountDTO -> {
            BillCountVO billCountVO = new BillCountVO();
            if (ObjectUtil.isNotNull(billCountDTO)) {
                BeanUtil.copyProperties(billCountDTO, billCountVO);
            }
            billCountVO.setTypeName(typeName);
            return billCountVO;
        }).collect(Collectors.toList());
    }

    /**
     * @param queryParams
     * @return
     */
    public Result<List<?>> goodsList(BillQueryParams queryParams) {
        //当前登录对象
        LoginUser loginUser = LogInUserUtil.get();
        List<?> list = goodsListDispatch.dispatch("goodsList", queryParams.getBillSource(), queryParams.getBillNo(), loginUser);
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000002, list);
    }

    /**
     * 结算操作
     * @param billNo
     * @param settleStatus
     * @return
     */
    @Transactional
    public Result<String> settlementBill(String billNo, boolean settleStatus) {
        Assert.hasLength(billNo, "参数[billNo]不能为空");
        //当前登录对象
        LoginUser loginUser = LogInUserUtil.get();
        FinaBill finaBill = finaBillService.queryBillByBillNo(billNo, loginUser);
        new BillCheck(finaBill).checkNull("对账单不存在").checkSettle("对账单没有完成");
        //结算状态需要判断金额是否满足
        if(settleStatus){
            if(finaBill.getPayAmount().compareTo(finaBill.getAmount()) < 0){
                 log.info("金额:{},支付金额:{}",finaBill.getAmount(),finaBill.getPayAmount());
                 throw  BusinessExceptionFactory.newException("对账单没有支付完成");
            }
            //剩余额度
            BigDecimal amount = finaBill.getPayAmount().subtract(finaBill.getAmount());
            //把多余的金额转移到下个订单
            if(amount.compareTo(BigDecimal.ZERO) > 0){
                //查询下个订单
              FinaBill nextBill =  finaBillService.getNextBill(billNo,finaBill.getCustomerCode(),finaBill.getBillType(),loginUser);
              new AbstractCheck<>(nextBill).checkNull("没有多余的可结算的对账单");
             //把多余金额迁移到下一个对账单中
                BillPayBuilder billPayBuilder = new BillPayBuilder();
                billPayBuilder.appendBillNo(nextBill.getBillNo()).appendAmount(amount)
                        .appendPayType(PayTypeEnum.BILL.getValue())
                        .appendDesc("费用来源:"+finaBill.getBillNo())
                        .appendCreate(loginUser);
                //保存支付记录信息
                if (!finaBillPayService.save(billPayBuilder.bulid())) {
                    log.info("保存付款单接口异常,参数:{}", JSON.toJSONString(billPayBuilder.bulid()));
                    throw BusinessExceptionFactory.newException("保存付款单接口异常");
                }
                BillAmountChangeDTO billAmountChangeDTO = new BillAmountChangeDTO(nextBill.getBillNo(),nextBill.getPayAmount().add(amount),nextBill.getUpdateVersion());
                if(!finaBillService.updatePayAmount(billAmountChangeDTO,loginUser)){
                    throw  BusinessExceptionFactory.newException("更新对账单付款金额");
                }
            }
        }
        BillBuilder billBuilder = new BillBuilder();
        billBuilder.appendEdit(loginUser).appendCode(finaBill.getBillNo()).appendTime(LocalDateTime.now())
                .appendOrderStatus(BillStatusEnum.SETTLEMENT.getValue());
        finaBillService.edit(billBuilder.bulid(), loginUser);
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000002, billNo);
    }

    /**
     * 加工对账单明细
     *
     * @param createParams
     * @return
     */
    public Result<List<BusinessGoodsVO>> businessGoodsList(BillCreateParams createParams) {
        //当前登录对象
        LoginUser loginUser = LogInUserUtil.get();
        //查询采购单列表
        List<String> orderNos = createParams.getOrderNos();
        if (ObjectUtil.isEmpty(orderNos)) {
            return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000002, new ArrayList<>());
        }
        Map<String, BigDecimal> inRecordMap = new HashMap<>();

        //查询加工单号
        List<ProdBusiness> prodBusinesses = prodBusinessService.listByOrderNos(orderNos, BusinessTypeEnum.IN.getValue(), loginUser);
        prodBusinesses.forEach(prodBusiness -> {
            inRecordMap.put(prodBusiness.getBusinessCode(), NumberUtil.null2Zero(prodBusiness.getPrice()));
        });
        List<ProdBusinessIn> records = prodBusinessInService.listAll(orderNos, loginUser);

        Map<String, MaterialModelVO> modelMap = new HashMap<>();
        final List<BigDecimal> totalPriceList = new ArrayList<>();
        final List<BigDecimal> quantity = new ArrayList<>();
        List<BusinessGoodsVO> businessGoodsVOS = records.stream().map(prodBusinessIn -> {
            MaterialModelVO materialModelVO = modelMap.get(prodBusinessIn.getGoodsCode());
            if (ObjectUtil.isNull(materialModelVO)) {
                materialModelVO = goodsService.queryGoodsByCode(prodBusinessIn.getGoodsCode(), loginUser);
                modelMap.put(prodBusinessIn.getGoodsCode(), materialModelVO);
            }
            totalPriceList.add(prodBusinessIn.getQuantity().multiply(NumberUtil.null2Zero(inRecordMap.get(prodBusinessIn.getBusinessCode()))));
            quantity.add(prodBusinessIn.getQuantity());
            return new BusinessGoodsVOBuilder().append(prodBusinessIn).append(materialModelVO)
                    .appendPrice(NumberUtil.null2Zero(inRecordMap.get(prodBusinessIn.getBusinessCode())))
                    .appendTotalAmount(prodBusinessIn.getQuantity().multiply(NumberUtil.null2Zero(inRecordMap.get(prodBusinessIn.getBusinessCode()))))
                    .bulid();
        }).collect(Collectors.toList());
        //计算总价
        BusinessGoodsVO purchaseGoodsVO = new BusinessGoodsVO();
        purchaseGoodsVO.setBusinessCode("合计:");
        purchaseGoodsVO.setTotalAmount(totalPriceList.stream().reduce(BigDecimal::add).get());
        purchaseGoodsVO.setQuantity(quantity.stream().reduce(BigDecimal::add).get());
        businessGoodsVOS.add(purchaseGoodsVO);
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000002, businessGoodsVOS);
    }


}
